package cn.com.sina.finance.todolist.fragment;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import cn.com.sina.finance.todolist.R;
import cn.com.sina.finance.todolist.adapter.TodoListAdapter;
import cn.com.sina.finance.todolist.base.BaseFragment;
import cn.com.sina.finance.todolist.bean.ApiResponse;
import cn.com.sina.finance.todolist.bean.PageData;
import cn.com.sina.finance.todolist.bean.TodoBean;
import cn.com.sina.finance.todolist.event.DeleteTodoEvent;
import cn.com.sina.finance.todolist.net.HttpCallback;
import cn.com.sina.finance.todolist.net.HttpUtil;
import cn.com.sina.finance.todolist.util.ToastUtil;

/**
 * @author yuebo
 * @date 2024/10/21
 */
public class TodoListFragment extends BaseFragment {

    private SmartRefreshLayout smartRefreshLayout;
    private RecyclerView recyclerView;
    private TodoListAdapter adapter;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_todo_list;
    }

    @Override
    public void initView() {
        smartRefreshLayout = viewHolder.getView(R.id.smartRefreshLayout);
        recyclerView = viewHolder.getView(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new TodoListAdapter(getContext());
        recyclerView.setAdapter(adapter);

        fetchTodoList(false);
    }

    @Override
    public void initListener() {
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageIndex++;
                fetchTodoList(true);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageIndex = 1;
                fetchTodoList(false);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeleteEvent(DeleteTodoEvent event) {
        pageIndex = 1;
        fetchTodoList(false);
    }

    private int pageIndex = 1;

    private void fetchTodoList(boolean isLoadMore) {
        String url = "http://chenyuebo.cn/getTodoList?pageSize=10&pageIndex=" + pageIndex;
        HttpUtil.get(url, new HttpCallback() {
            @Override
            public void onSuccess(String data) {
                // 网络回调后，无论解决如何，先停止刷新动画
                smartRefreshLayout.finishRefresh();
                smartRefreshLayout.finishLoadMore();
                showEmptyView(adapter.getItemCount() <= 0);

                // 解析数据
                ApiResponse<PageData<TodoBean>> response = new Gson().fromJson(data, new TypeToken<ApiResponse<PageData<TodoBean>>>() {
                }.getType());
                if (response == null) {
                    ToastUtil.showLongToast(getContext(), "解析数据失败");
                    return;
                }
                if (response.code == 0) {
                    List<TodoBean> list = response.data.rows;
                    Log.d("todo", "获取Todo列表数据成功 todoList=" + list);
                    updateAdapter(list, isLoadMore);
                    smartRefreshLayout.setNoMoreData(list == null || list.isEmpty());
                } else {
                    ToastUtil.showLongToast(getContext(), "获取Todo列表数据失败:" + response.msg);
                }
            }

            @Override
            public void onFail(int code, String msg, Throwable e) {
                // 网络回调后，无论解决如何，先停止刷新动画
                smartRefreshLayout.finishRefresh();
                smartRefreshLayout.finishLoadMore();
                showEmptyView(adapter.getItemCount() <= 0);

                ToastUtil.showLongToast(getContext(), "网络请求失败" + e.getMessage());
            }
        });
    }

    private void updateAdapter(List<TodoBean> list, boolean isLoadMore) {
        if (isLoadMore) {
            adapter.appendData(list);
        } else {
            adapter.setDataList(list);
        }
        showEmptyView(adapter.getItemCount() <= 0);
    }

    private void showEmptyView(boolean isEmpty) {
        viewHolder.setVisible(R.id.recyclerView, !isEmpty);
        viewHolder.setVisible(R.id.v_no_data, isEmpty);
    }
}
